/**
 * 
 */
package com.maywide.jdp.system.service;

import java.util.ArrayList;
import java.util.List;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;

import com.maywide.jdp.core.exception.AppException;
import com.maywide.jdp.core.vo.Context;
import com.maywide.jdp.system.annotation.JSON;
import com.maywide.jdp.system.bean.ButtonBean;
import com.maywide.jdp.system.bean.OrganizationBean;
import com.maywide.jdp.system.bean.RoleBean;
import com.maywide.jdp.system.entities.Organization;
import com.maywide.jdp.system.entities.Role;
import com.maywide.jdp.system.vo.Task;

/**
 * <b>任务Service</b><br>
 * 
 * @author luoyang
 * @version 1.0
 * @since JDK1.6
 */
@Controller("taskService")
public class TaskServiceImpl implements TaskService {
	private static final String DESKTOP_PAGE = "desktopPage";
	private static final String SELECT_ENTITY_PAGE = "selectEntityPage";
	
	/**
	 * 
	 */
	private ButtonBean buttonBean = null;

	/**
	 * 
	 */
	private RoleBean roleBean = null;

	/**
	 * 
	 */
	private OrganizationBean organizationBean = null;


	/**
	 * @param buttonBean
	 *            the buttonBean to set
	 */
	@Autowired
	@Qualifier("buttonBean")
	public void setButtonBean(ButtonBean commandBean) {
		this.buttonBean = commandBean;
	}

	/**
	 * @param operatorBean
	 *            the operatorBean to set
	 */
	@Autowired
	@Qualifier("roleBean")
	public void setRoleBean(RoleBean roleBean) {
		this.roleBean = roleBean;
	}

	/**
	 * @param organizationBean
	 *            the organizationBean to set
	 */
	@Autowired
	@Qualifier("organizationBean")
	public void setOrganizationBean(OrganizationBean organizationBean) {
		this.organizationBean = organizationBean;
	}

	@JSON
	@RequestMapping("/getContext.json")
	@Override
	public Context getContext(HttpServletRequest request,
			HttpServletResponse response, HttpSession session) throws Exception {
		Object obj = session.getAttribute("context");
		if (obj == null)
			throw new AppException("会话超时，请重新登陆!");
		Context context = (Context) obj;
		return context;
	}

	@JSON
	@RequestMapping("/getTasks.json")
	public List<Task> getTasks(
			@RequestParam(value = "busnessCode")String busnessCode, 
			HttpServletRequest request,
			HttpServletResponse response, 
			HttpSession session)
			throws Exception {
		Object obj = session.getAttribute("context");
		if (obj == null)
			throw new AppException("会话超时!");
		Context context = (Context) obj;

		String operatorID = context.getOperatorID();
		List<Task> tasks = buttonBean.findTasks(busnessCode, operatorID);

		return tasks;
	}

	@JSON
	@RequestMapping("/showEntity.json")
	@Override
	public List<Organization> showEntity(HttpServletRequest request,
			HttpServletResponse response, HttpSession session)
			throws Exception {
		Object obj = session.getAttribute("context");
		if (obj == null)
			throw new AppException("会话超时，请重新登陆!");
		List<Organization> organizations = null;
		Context context = (Context) obj;
		String[] strOrganizations = context.getOrganizations();
		if (strOrganizations != null) {
			int n = strOrganizations.length;
			for (int i = 0; i < n; i++) {
				String strOrganization = strOrganizations[i];
				String[] org = strOrganization.split(",");
				Organization organization = new Organization();
				organization.setId(org[0]);
				organization.setCode(org[1]);
				organization.setName(org[2]);
				organization.setType(org[3]);
				if (organizations == null)
					organizations = new ArrayList<Organization>();
				organizations.add(organization);
			}
		}
		return organizations;
	}

	@RequestMapping(value = "/entryEntity.json")
	public void selectEntity(
			@RequestParam(value = "entityID", required = true) String currentOrgID,
			HttpServletRequest request, 
			HttpServletResponse response,
			HttpSession session) throws Exception {
		Object obj = session.getAttribute("context");
		if (obj == null)
			throw new AppException("会话超时，请重新登陆!");
		Context context = (Context) obj;

		String operatorID = context.getOperatorID();
		// 设置当前机构路径
		if (currentOrgID != null && !"".equals(currentOrgID)) {
			Organization currentOrg = (Organization) organizationBean
					.load(currentOrgID);
			StringBuffer buf = new StringBuffer(currentOrgID);
			Organization parent = currentOrg.getParent();
			while (parent != null) {
				buf.append("/").append(parent.getId());
				parent = parent.getParent();
			}
			context.setOrgPath(buf.toString());
			String currentOrganization = new StringBuffer()
					.append(currentOrgID).append(",").append(
							currentOrg.getCode()).append(",").append(
							currentOrg.getName()).append(",").append(currentOrg.getType()).toString();
			context.setCurrentOrganization(currentOrganization);
		}

		List<Role> roles = roleBean.findByOperatorID(operatorID);
		List<Role> selectedRoles = null;
		for (Role role : roles) {
			Organization entity = role.getEntity();
			if (role.isActive() && entity != null
					&& entity.getId().equals(currentOrgID)) {
				if (selectedRoles == null)
					selectedRoles = new ArrayList<Role>();
				selectedRoles.add(role);
			}
		}

		if (selectedRoles != null && !selectedRoles.isEmpty()) {
			String[] roleArray = new String[selectedRoles.size()];
			int i = 0;
			for (Role selectedRole : selectedRoles) {
				if (!selectedRole.isActive())
					continue;
				StringBuffer buf = new StringBuffer();
				buf.append(selectedRole.getId());
				buf.append(",");
				buf.append(selectedRole.getCode());
				buf.append(",");
				buf.append(selectedRole.getName());
				buf.append(",");
				buf.append(selectedRole.getEntity().getCodePath());
				roleArray[i] = buf.toString();
				i++;
			}
			context.setRoles(roleArray);
			session.setAttribute("context", context);
			String desktopPage = request.getSession().getServletContext().getInitParameter(DESKTOP_PAGE);
			response.sendRedirect(desktopPage);
		} else {
			String selectEntityPage = request.getSession().getServletContext().getInitParameter(SELECT_ENTITY_PAGE);
			response.sendRedirect(selectEntityPage);
		}
	}
}
